package com.ylb.rent.util;

import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @AUTHOR:游李滨
 * @DATE:2023/6/29 11:40
 */
@Component
public class MinioUtil {

    @Autowired
    MinioClient minioClient;



    @Value(value = "${minio.bucket}")
    private String bucket;

    @Value(value = "${minio.host}/${minio.bucket}/")
    private String url;
    private String getSuffix(String fileName){
        int i = fileName.lastIndexOf(".");
        return fileName.substring(i);
    }

    /**
     *  名字:年月日+UUID 8位
     *
     * */

    private String generateFileName(MultipartFile file){
        StringBuilder sb = new StringBuilder();

        LocalDate now = LocalDate.now();
        sb.append(now.getYear());
        sb.append(now.getMonthValue());
        sb.append(now.getDayOfMonth());

        String substring = UUID.randomUUID().toString().substring(0, 8);
        sb.append(substring);
        return sb.toString()+getSuffix(file.getOriginalFilename());
    }

    public String put(MultipartFile file) throws IOException, NoSuchAlgorithmException, InsufficientDataException, InternalException, InvalidResponseException, InvalidKeyException, InvalidBucketNameException, XmlParserException, ErrorResponseException {

        String fileName=generateFileName(file);
        InputStream inputStream = file.getInputStream();
        long size = file.getSize();
        PutObjectOptions putObjectOptions = new PutObjectOptions(size,-1);
        putObjectOptions.setContentType(file.getContentType());
        minioClient.putObject(bucket,fileName,inputStream,putObjectOptions);

        return generateFileUrl(fileName);
    }

    private String generateFileUrl(String fileName){

        return this.url+fileName;
    }


}
